#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include "param.h"
#include "types.h"
#include "defs.h"

#define INPUT_DIR "tmp.split"
#define OUTPUT_DIR "tmp.merge"
#define  OUTPUT_POSTFIX ".merge"
#define INPUT_POSTFIX ".split"

threadinfo tinfo[MAX_THREAD_NUM];
int thread_num;
int numa_opt;

int
main (int argc, char **argv) {
    int i;
    int knum, st;
    char input_dir[MAX_NAME_LEN], output_dir[MAX_NAME_LEN];
    char *a_ptr, *s_tmp;
    thread_num = MAX_THREAD_NUM;
    numa_opt = 0;
    input_dir[0] = 0;
    output_dir[0] = 0;
    s_tmp = NULL;
    strcat (input_dir, INPUT_DIR);
    strcat (output_dir, OUTPUT_DIR);
    knum = st = 4;
    for (i = 1; i < argc; i++) {
        a_ptr = argv[i];
        if (*a_ptr == '-') {
            a_ptr++;
            switch (*a_ptr)
            {
            case 'i':
            a_ptr++;
            sscanf (a_ptr,"%ms",&s_tmp);
            if (strlen(s_tmp) + strlen (INPUT_POSTFIX)
                >= MAX_NAME_LEN) {
                printf ("MAX_NAME_LEN reached.\n");
                free (s_tmp);
                break;
            }
            input_dir[0] = 0;
            output_dir[0] = 0;
            strcat (input_dir, s_tmp);
            strcat (output_dir, s_tmp);
            strcat (input_dir, INPUT_POSTFIX);
            strcat (output_dir, OUTPUT_POSTFIX);
            break;
            case 'k':
            a_ptr++;
            sscanf (a_ptr, "%d", &knum);
            break;
            case 's':
            a_ptr++;
            sscanf (a_ptr, "%d", &st);
            break;
            case 'n':
            if (strcmp (a_ptr, "numa") == 0)
                numa_opt = 1;
            break;
            default:break;
            }
        }
    }
    if (s_tmp != NULL)  free (s_tmp);
    if (mkdir (output_dir, S_IRWXU) == -1)
        HANDLE_ERROR ("main", "mkdir",1);
    if (file_init (input_dir, output_dir) == -1)
        HANDLE_ERROR ("main", "file_init",0);
    if (thread_init (st,knum) == -1)
        HANDLE_ERROR ("main", "thread_init",0);
    if (thread_create () == -1)
        HANDLE_ERROR ("main", "thread_create",0);
    if (thread_join () == -1)
        HANDLE_ERROR ("main", "thread_init", 0);
    printf ("MAIN: All threads exited. Main thread exiting...\n");
    return EXIT_SUCCESS;
    error:
    return EXIT_FAILURE;
}
